package cn.kxx.controller;


import cn.kxx.constant.MessageConstant;
import cn.kxx.constant.RedisConstant;
import cn.kxx.entity.Result;
import cn.kxx.exception.BusinessException;
import cn.kxx.pojo.Member;
import cn.kxx.service.MemberService;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api("会员管理模块")
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Reference
    private MemberService memberService;
    @ApiOperation("登入")
    @PostMapping("/login")
    public Result login(@RequestBody Map map, HttpServletResponse response){
//        校验验证码
//        求出手机号和验证码
        String telephone = map.get("telephone").toString();
        String validateCode = map.get("validateCode").toString();
        if (StringUtils.isEmpty(telephone)||StringUtils.isEmpty(validateCode)){
            throw new BusinessException("手机号或验证码为空");
        }

//        d对比
        Object code = redisTemplate.opsForValue().get(RedisConstant.SENDTYPE_ORDER + ":" + telephone);
        if (code==null){
            throw new BusinessException("验证码已失效");
        }
        if (!code.equals(validateCode)){
            throw new BusinessException("验证码错误");
        }

//        判断是否为会员

       Member member = memberService.findByTelephone(telephone);
        if (member == null){
            Member member1 = new Member();
            member1.setPhoneNumber(telephone);
            member1.setRegTime(new Date());
            memberService.add(member1);
        }


//        生成cookie
        Cookie cookie = new Cookie("login_member_telephone",telephone);
        cookie.setMaxAge(60*60*24*2);
        cookie.setPath("/");
        response.addCookie(cookie);
        String memberJsonStr = JSONObject.toJSONString(member);
        redisTemplate.opsForValue().set(telephone,memberJsonStr,48, TimeUnit.HOURS);
        return new Result(true, MessageConstant.LOGIN_SUCCESS);

    }
}
